﻿// EnumerableSurrogate.cs
//
// Copyright 2008 by Burt Harris
// Licensed under the Microsoft Public License (Ms-PL)
// See: http://www.codeplex.com/yaml/license
//
namespace YaTools.Yaml.Serialization
{
    using System;
    using System.Collections;
    using System.Diagnostics;
    using System.Runtime.Serialization;
    using System.Security.Permissions;

    [DebuggerDisplay("EnumerableSurrogate")]
    [Obsolete("Replace with Emitter/Mode/Waypoint")]
    public sealed class EnumerableSurrogate : YamlSurrogate 
    {
        // private sngleton constructor
        private EnumerableSurrogate() { }

        static Uri s_baseUri = new Uri("tag:yatools.net,2009:enumerable,");

        protected override Uri BaseUri
        {
            get { return s_baseUri; }
        }

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
        {
            var writer = context.YamlWriter();

            var enumerable = obj as IEnumerable;
            if (enumerable == null)
                throw new ArgumentNullException("obj");

            if (writer.BeginList(obj, GetUri(obj.GetType()), false))
            {
                try
                {
                    foreach (object member in enumerable)
                    {
                        writer.WriteItem(member, Globals.TypeOfObject);
                    }
                }
                finally
                {
                    writer.EndList();
                }
            }
        }

        [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
        public override object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
        {
            throw new NotImplementedException();
        }

        public static EnumerableSurrogate Instance { get { return _instance; } }
        private static EnumerableSurrogate _instance = new EnumerableSurrogate();
    }
}
